package com.gulimall.gulimallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gulimall.common.constant.ProductConstant;
import com.gulimall.gulimallproduct.dao.AttrAttrgroupRelationDao;
import com.gulimall.gulimallproduct.dao.AttrGroupDao;
import com.gulimall.gulimallproduct.dao.CategoryDao;
import com.gulimall.gulimallproduct.entity.AttrAttrgroupRelationEntity;
import com.gulimall.gulimallproduct.entity.AttrGroupEntity;
import com.gulimall.gulimallproduct.entity.CategoryEntity;
import com.gulimall.gulimallproduct.service.CategoryService;
import com.gulimall.gulimallproduct.vo.AttrGroupRelationVo;
import com.gulimall.gulimallproduct.vo.AttrRespVo;
import com.gulimall.gulimallproduct.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.gulimallproduct.dao.AttrDao;
import com.gulimall.gulimallproduct.entity.AttrEntity;
import com.gulimall.gulimallproduct.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    AttrAttrgroupRelationDao relationDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //保存基本呢数据
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        //保存关联关系，如果没设置分组信息，就不用保存关联关系
        if(attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPR_BASE.getCode()&&attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity=new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    /**
     * 获取分类规格参数
     * @param params
     * @param catelogId
     * @return
     */
    @Override
    public PageUtils QueryAttrBasePage(Map<String, Object> params, Long catelogId,String type) {
        QueryWrapper<AttrEntity> attrEntityQueryWrapper =
                new QueryWrapper<AttrEntity>()
                        .eq("attr_type","base".equalsIgnoreCase(type)
                                ?ProductConstant.AttrEnum.ATTR_TYPR_BASE.getCode()
                                :ProductConstant.AttrEnum.ATTR_TYPR_SALE.getCode());
        if(catelogId!=0L){
            attrEntityQueryWrapper.eq("catelog_id",catelogId);
        }
        Object o = params.get("key");
        if(o!=null&&!StringUtils.isEmpty(o.toString())){

            attrEntityQueryWrapper.and(wrapper->{
                wrapper.eq("attr_id",o.toString()).or().like("attr_name",o.toString());
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                attrEntityQueryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<Object> collect = records.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //"catelogName": "手机/数码/手机", //所属分类名字
            // "groupName": "主体", //所属分组名字
            Long catelogId1 = attrRespVo.getCatelogId();

                CategoryEntity categoryEntity = categoryDao.selectById(catelogId1);
                if(categoryEntity!=null){
                    attrRespVo.setCatelogName(categoryEntity.getName());
                }
                if(type.equalsIgnoreCase("base")){
                    AttrAttrgroupRelationEntity attrAttrgroupRelationEntity =
                            relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrRespVo.getAttrId()));
                    //如果在新增属性的时候没有设置分组，就不要查找了，会报空指针的
                    if (attrAttrgroupRelationEntity != null&&attrAttrgroupRelationEntity.getAttrGroupId()!=null) {
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                        if (attrGroupEntity != null) {
                            attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                        }
                    }
                }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(collect);
        return pageUtils;
    }


    /**
     *
     * 分页模糊查询  ，比如按分类查属性、按属性类别查属性
     */
    /*@Override // AttrServiceImpl.java
    public PageUtils QueryAttrBasePage(Map<String, Object> params, Long catelogId,
                                       String attrType) { // 表明查询的是 属性类型[0-销售属性，1-基本属性，2-既是销售属性又是基本属性]
        // 传入的attrType是"base"或其他，但是数据库存的是 "0"销售 / "1"基本
        // 属性都在pms_attr表中混合着
        QueryWrapper<AttrEntity> wrapper =
                new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(attrType)
                        ?ProductConstant.AttrEnum.ATTR_TYPR_BASE.getCode()
                        :ProductConstant.AttrEnum.ATTR_TYPR_SALE.getCode());

        // 如果参数带有分类id，则按分类查询
        if (catelogId != 0L ) {
            wrapper.eq("catelog_id", catelogId);
        }
        // 支持模糊查询，用id或者name查
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        // 正式查询满足条件的属性
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        List<AttrEntity> records = page.getRecords();
        PageUtils pageUtils = new PageUtils(page);

        // 查到属性后还要结合分类名字、分组名字(分类->属性->分组) 封装为AttrRespVo对象
        List<AttrRespVo> attrRespVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            // 1.设置分类和分组的名字  先获取中间表对象  给attrRespVo 封装分组名字
            if("base".equalsIgnoreCase(attrType)){ // 如果是规格参数才查询，或者说销售属性没有属性分组，只有分类
                // 根据属性id查询关联表，得到其属性分组
                AttrAttrgroupRelationEntity entity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (entity != null && entity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(entity);
                    // 设置属性分组的名字
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            // 2.查询分类id 给attrRespVo 封装三级分类名字
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }
*/
    /**
     * 查询属性详情
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity byId = this.getById(attrId);
        BeanUtils.copyProperties(byId,attrRespVo);
        if(attrRespVo.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPR_BASE.getCode()){
            //设置分组信息
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity
                    = relationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId)
            );
            if(attrAttrgroupRelationEntity!=null){
                attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if(attrGroupEntity!=null){
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //设置分类信息
        Long catelogId = byId.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity!=null){
            String name = categoryEntity.getName();
            attrRespVo.setCatelogName(name);
        }
        //设置分类信息
        return attrRespVo;
    }

    /**
     * 修改属性
     * @param attr
     */
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        //修改基本属性
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        if(attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPR_BASE.getCode()){
            //修改关联表中的分组id
            AttrAttrgroupRelationEntity relationEntity=new AttrAttrgroupRelationEntity();
            if(attr.getAttrGroupId()!=null){
                relationEntity.setAttrGroupId(attr.getAttrGroupId());
            }
            relationEntity.setAttrId(attr.getAttrId());
            Integer i = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if(i>0&&attr.getAttrGroupId()!=null){
                relationDao.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            }
            else if (i==0&&attr.getAttrGroupId()!=null){
                relationDao.insert(relationEntity);
            }

        }
    }

    /**
     * 获取属性分组的关联的所有属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrGroupId = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().
                        eq("attr_group_id", attrgroupId));
        List<Long> collect = attrGroupId.stream().map(attr -> attr.getAttrId())
                .collect(Collectors.toList());
        if(collect==null||collect.size()==0){
            return null;
        }
        List<AttrEntity> attrEntities = this.listByIds(collect);
        return attrEntities;
    }

    /**
     * 删除属性与分组的关联关系
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        //批量删除
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map(item -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(collect);
    }

    /**
     * 13、获取属性分组没有关联的其他属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNorelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1属性分组必须是同一一个分类下的
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2必须是其他分类没有关联过的属性
        //2.1获取其他的分组id，并排除关联的属性id
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        //获取所有的分组id
        List<Long> collect = attrGroupEntities.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //根据分组id获取所有的属性id
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities =
                relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id",collect));
        List<Long> collect1 = attrAttrgroupRelationEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //去属性表中查找对应的值
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId)
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPR_BASE.getCode());
        if(collect1!=null&&collect1.size()>0){
            wrapper.notIn("attr_id",collect1);
        }
        String string = params.get("key").toString();
        if(!StringUtils.isEmpty(string)){
            wrapper.and(w->{
                w.eq("attr_id",string).or().like("attr_name",string);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    /**
     * 在所有属性集合中调出检索属性
     * @param attrids
     * @return
     */
    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrids) {
        return baseMapper.selectSearchAttrIds(attrids);
    }
}